package com.ken.forum.services.impl;

import com.alibaba.druid.util.StringUtils;
import com.ken.forum.common.AppResult;
import com.ken.forum.common.ResultCode;
import com.ken.forum.dao.ArticleReplyMapper;
import com.ken.forum.exception.ApplicationException;
import com.ken.forum.model.ArticleReply;
import com.ken.forum.services.IArticleReplyService;
import com.ken.forum.services.IArticleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;


@Slf4j
@Service
public class ArticleReplyServiceImpl implements IArticleReplyService {

    @Resource
    private IArticleService articleService;

    @Resource
    private ArticleReplyMapper articleReplyMapper;

    @Override
    public List<ArticleReply> selectByArticleId(Long articleId) {
        if (articleId == null || articleId < 0) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        List<ArticleReply> articleReplies = articleReplyMapper.selectByArticleId(articleId);

        return articleReplies;
    }

    @Override
    public void create(ArticleReply articleReply) {
        if (articleReply == null || StringUtils.isEmpty(articleReply.getContent()) || articleReply.getPostUserId() == null || articleReply.getPostUserId() < 0 || articleReply.getArticleId() == null || articleReply.getArticleId() < 0) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //设置默认值
        articleReply.setLikeCount(0); // 点赞数
        articleReply.setState((byte) 0); // 状态
        articleReply.setDeleteState((byte) 0); // 是否删除
        Date date = new Date();
        articleReply.setCreateTime(date); // 创建时间
        articleReply.setUpdateTime(date); // 更新时间

        int row = articleReplyMapper.insertSelective(articleReply);
        if (row != 1) {
            // 打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        //更新文章数
        articleService.updateArticleCountById(articleReply.getArticleId());

        // 打印日志
        log.info(ResultCode.SUCCESS.toString() + " 回复发布成功, articleId = " + articleReply.getArticleId());

    }
}
